#include"MyPlayer.h"
int bAudioThreadRunning=0;
int sample_rate=0;
int samples=0;
int TryGetAudioCodec(FF_AUDIOINFO*audioinfo,AVFormatContext *fmt_ctx){
    audioinfo->idx=FindAudioCodec(fmt_ctx);
    if(audioinfo->idx!=-1){
       AVCodec *dec = NULL;
       audioinfo->stream=fmt_ctx->streams[audioinfo->idx];
       audioinfo->codec=audioinfo->stream->codec;
       dec=avcodec_find_decoder(audioinfo->codec->codec_id);
       if(dec==NULL){
          printf("Find Audio dec failed %s\n",avcodec_get_name(audioinfo->codec->codec_id)); 
		  return -1;
       }
       if(avcodec_open2(audioinfo->codec,dec,NULL)<0){
		  printf("Open Audio dec failed %s\n",avcodec_get_name(audioinfo->codec->codec_id)); 
		  return -1;
	   }else{
          sample_rate=audioinfo->codec->sample_rate;
          samples=audioinfo->codec->frame_size;
          audioinfo->pSwr=swr_alloc();
          audioinfo->pSwr=swr_alloc_set_opts(audioinfo->pSwr, 
          AV_CH_LAYOUT_STEREO,AV_SAMPLE_FMT_S16,sample_rate,
          av_get_default_channel_layout(audioinfo->codec->channels),
          audioinfo->codec->sample_fmt,sample_rate, 
          0, NULL);
          swr_init(audioinfo->pSwr);
          audioinfo->length = av_samples_get_buffer_size(NULL,av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO),samples, AV_SAMPLE_FMT_S16,1);
          printf("audioLength:%d size:%d\n",audioinfo->length,audioinfo->codec->frame_size);
          //system("pause");
        }
    }
    return audioinfo->idx;
}

#define MAX_AUDIO_FRAME_SIZE 192000
int TryDecAudioPacket(FF_AUDIOINFO*audioinfo,AVPacket*packet,AVFrame*pFrame){
    double pts=0;
	int frameFinished=0;
    int ret=avcodec_decode_audio4(audioinfo->codec,pFrame,&frameFinished,packet);
	if (ret < 0)return -1;
    if(packet->dts!=AV_NOPTS_VALUE){
       pts=packet->dts;
    }else
	if((packet->dts == AV_NOPTS_VALUE)&&
	   (pFrame->opaque!=NULL)&&
	   (*(uint64_t*)pFrame->opaque != AV_NOPTS_VALUE)){
	   pts=*(uint64_t *)pFrame->opaque;	   
	}
	pts*=av_q2d(audioinfo->stream->time_base);
    if(frameFinished){            
       uint8_t*buffer=malloc(MAX_AUDIO_FRAME_SIZE*2);
       int  ret=swr_convert(audioinfo->pSwr,&buffer,48000,(const uint8_t**)pFrame->data,pFrame->nb_samples);
       int  decoded_data_size=av_samples_get_buffer_size(NULL,2,ret,AV_SAMPLE_FMT_S16,1); 
       //printf("DataSize:%d ret:%d sample:%d\n",decoded_data_size,ret,pFrame->nb_samples);
       PushAudioPacket(buffer,decoded_data_size,(int)(pts*1000));  
    }
    return FFMIN(ret, packet->size);
}